const _ = require('lodash');

/**
 * @api {get} /api/admin/v1/permissions/find 权限列表
 * @apiGroup AdminPermissions
 * @apiDescription 权限管理-权限列表
 * @apiPermission 管理员(查看权限权限)
 * @apiVersion 1.0.0
 */
exports.find = function ({query}, {models: {Permissions, PermissionsRoles}}) {
    return PermissionsRoles.findAll({where: {role: query.role}, raw: true}).then(function (permissionsRoles) {
        let permissions_ids = _.map(permissionsRoles, 'permission_id');
        let where = {};
        if (query.permissions == 'checked') {
            where = {id: permissions_ids};
        }
        return Permissions.findAll({
            where: where,
            order: [['object_type', 'asc'], ['action_type', 'asc']],
            raw: true
        }).then(function (permissions) {
            for (let i in permissions) {
                let permission = permissions[i];
                permission.checked = _.includes(permissions_ids, permission.id);
            }
            return {count: permissions.length, rows: permissions};
        });
    });
}

/**
 * @api {post} /api/admin/v1/permissions/save 权限保存修改
 * @apiGroup AdminPermissions
 * @apiDescription 权限管理-权限保存修改
 * @apiPermission 管理员(编辑权限权限)
 * @apiVersion 1.0.0
 */
exports.save = function ({body}, {models: {PermissionsRoles}}) {
    return PermissionsRoles.saveV2(body);
}